﻿/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.load {
	
	import lads.flad.interfaces.ILoadable;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * DataLoader: A wrapper for ASCII data loading.
	 * @author Dale J Williams
	 * @version 1.1
	 */
	public class DataLoader extends EventDispatcher implements ILoadable {
		
		protected var _loader			:URLLoader;
		protected var _url				:String;
		protected var _data				:*;
		protected var _loadPercent		:Number;
		protected var _loadCompleted	:Boolean;
		protected var _name				:String;
		
		public function DataLoader($url:String=null) {
			_url = $url;
			init();
		}
		
		private function init():void {
			_loader = new URLLoader();
			_loadPercent = 0;
		}
		
		public function load($url:String=null):void {
			if ($url) _url = $url;
			_loader.addEventListener(Event.COMPLETE, loadComplete);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			_loader.load(new URLRequest(_url));
		}
		
		private function loadComplete(e:Event):void {
			_data = _loader.data;
			_loadPercent = 1;
			_loadCompleted = true;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function loadError(e:Event):void {
			dispatchEvent(new ErrorEvent("Could not find data: " + _url));
		}
		
		public function get url():String { return _url; }		
		public function set url(value:String):void {
			_url = value;
		}
		
		public function get data():* { return _data; }
		
		public function get loadCompleted():Boolean { return _loadCompleted; }
		
		public function get loadPercent():Number { return _loadPercent; }
		
		public function get name():String { return _name; }		
		public function set name(value:String):void {
			_name = value;
		}
		
	}
	
}